<?php
namespace addon\cms\logic;
// +----------------------------------------------------------------------
// | Author: xiaojun <920668625@qq.com>
// +----------------------------------------------------------------------
use app\common\logic\LogicBase;
use think\Db;
use \tpfcore\Core;
use addon\wechat_material\logic\WechatMaterial;
use tpfcore\web\Curl;
use addon\wechat_config\logic\WechatReceive;

class MiniReceiveText extends LogicBase
{
	public function receiveTextFunc($object){

		$content = '';

        $keyword = trim($object->Content);
        
		$replydata = WechatReceive::materialKeywordList($keyword);

		$data['touser'] = (String)$object->FromUserName ;

		if($replydata)
		{
			switch(WECHAT_REPLY_TYPE)
            {
                case 'image':
                	$content = array();
                    $content = ['MsgType'=>'image','MediaId'=>$replydata['media_id']];
                    break;
                case 'voice':
                	$content = array();
                    $content = [
						'MsgType'     => 'voice',
						'Title'       => $replydata['name'],
						'Description' => '来自：'.WECHAT_NAME,
						'MusicUrl'    => WechatFunc::format_url($replydata['local_url']),
						'HQMusicUrl'  => WechatFunc::format_url($replydata['local_url'])
                    ];
                    break;
                case 'video':
                    $content = array();
                    $content = [
						'MsgType'      => 'video',
						'MediaId'      => $replydata['media_id'],
						'ThumbMediaId' => '',
						'Title'        => $replydata['name'],
						'Description'  => $replydata['description']
                    ];
                    break;
                case 'news':
					$content = array();
                    $content[] = [
						'MsgType'     => 'news',
						'Title'       => $replydata['title'],
						'Description' => $replydata['description'],
						'PicUrl'      => WechatFunc::format_url($replydata['pic_url']),
						'Url'         => $replydata['url']?$replydata['url']:$replydata['content_source_url']
                    ];
                    $son_data = (new WechatMaterial())->newsMaterialList(['group_id'=>$replydata['id']],0,'id asc');
                    foreach ($son_data as $key => $value) {
                    	$content[] = [
							'MsgType'     => 'news',
							'Title'       => $value['title'],
							'Description' => $value['description'],
							'PicUrl'      => WechatFunc::format_url($value['pic_url']),
							'Url'         => $value['url']?$value['url']:$value['content_source_url']
                    	];
                    }
                    break;
                case 'text':
                    $content = '';
                    $content = strip_tags($replydata,'<a>');

                    preg_match_all('/\[([0-9a-z_]+)\]/i',$content,$matches);
                    foreach($matches[1] as $emoji){
						$info    = WechatFunc::getEemoj($emoji);
						//处理表情
						$content = str_replace('['.$emoji.']',WechatFunc::bytesToEmoji($info['utf16']),$content);
                    }

                    $data['msgtype'] = (String)$object->MsgType;

                	$data['text']['content'] = $content;

                break;
            }
		}else{
			//默认回复内容
			switch($object->MsgType)
			{
				case 'image':
					$data['msgtype'] = 'image';
	                $data['image']['media_id'] = 'q3oQpLPWOIB50tCKdR510qeNIGEQd9A0Ku7DJJmsTsXVeQZqq0sUMK2gbUyJZsYn';
	                $data['image']['picurl'] = 'this is image';
					break;
				case 'link':
					$data['msgtype'] = 'link';
	                $data['link']['title'] = urlencode('文章标题');
	                $data['link']['description'] = urlencode('好文章要分享');
	                $data['link']['url'] = 'https://www.tpframe.com';
	                $data['link']['thumb_url'] = 'https://www.bmob.cn/uploads/attached/app/logo/20180930/c02d430f-08b0-ec9c-d256-f14113dd5f90.PNG';
					break;
				case 'miniprogrampage':
					
				case 'text':

					$data['msgtype'] = (String)$object->MsgType;

                	$data['text']['content'] = urlencode('我们已经收到你的消息，请稍等....');//urlencode 解决中文乱码问题

					break;
				default:

					$data['msgtype'] = (String)$object->MsgType;

                	$data['text']['content'] = urlencode('对不起，我不知道您在说什么....');//urlencode 解决中文乱码问题
            }
			
		}

		$this->send($data);
		
	}

	//发送消息接口调用
    private function send($data){
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->getAccessToken();
        $data = urldecode(json_encode($data));
        Curl::post($url,$data);
    }
    //获取accesstoken
    private function getAccessToken() {
        $tokenFile = "access_token.txt";
        if(!file_exists($tokenFile)){
        	file_put_contents($tokenFile, "");
        }
        $data = json_decode(file_get_contents($tokenFile));

        //accesstoken有效期是7200秒，这里用到的文件缓存
        //注意：文件权限问题
        if(empty($data) || empty($data->expires_in) || $data->expires_in+7200<time()){		//表示数据不对或已过期
        	$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".MIMICHAT_APPID."&secret=".MIMICHAT_APPSECRET;
        	$res =  json_decode(file_get_contents($url));
        	if($res && !empty($res->access_token)){
        		$arr['expires_in'] = time() + 7200;
                $arr['access_token'] = $res->access_token;
                $fp = fopen($tokenFile, "w");
                fwrite($fp, json_encode($arr));
                fclose($fp);

                $access_token = $res->access_token;
        	}else{
        		die($res['errmsg']);
        	}
        }else{
        	$access_token = $data->access_token;
        }

        return $access_token;
    }
}